package com.github.wui.comm;


import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;


import java.util.ArrayList;
import java.util.List;

/**
 * package name : com.github.bimusic.widget
 * <p>
 * 堆叠卡片滑动布局
 *
 * @author karai
 * @DATE 2025/9/19
 */
public class StackCardSliderLayout extends FrameLayout {
    private final static String TAG = StackCardSliderLayout.class.getSimpleName();


    public interface IScrollListener {

        void onChange(boolean right, boolean left, boolean finish, int childCount);


    }

    private IScrollListener listener;

    /**
     * 默认操作从第一个开始
     */
    private int mActionCardNo = 0;


    RecyclerView.Adapter mAdapter = null;
    private float mMoveDistance;

    public StackCardSliderLayout(@NonNull Context context) {
        this(context, null);
    }

    public StackCardSliderLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public StackCardSliderLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int w = MeasureSpec.getSize(widthMeasureSpec);
        int h = MeasureSpec.getSize(heightMeasureSpec);
        int childCount = getChildCount();
        if (childCount == 0) {
            return;
        }
        if (getLayoutParams().width != LayoutParams.MATCH_PARENT && getLayoutParams().width != LayoutParams.WRAP_CONTENT) {

            // 自身
            w = getChildAt(0).getLayoutParams().width + 300;
        } else {
            w = MeasureSpec.makeMeasureSpec(w, MeasureSpec.AT_MOST); // 获取父元素的宽高
        }

        if (getLayoutParams().height != LayoutParams.MATCH_PARENT && getLayoutParams().height != LayoutParams.WRAP_CONTENT) {
            // 自身
            h = getChildAt(0).getLayoutParams().height + 300;

        } else {
            h = MeasureSpec.makeMeasureSpec(h, MeasureSpec.AT_MOST);
        }

        for (int i = 0; i < childCount; i++) {
            View childView = getChildAt(i);
            int measuredHeight = getMeasuredHeight() - getMeasuredHeight() / 6;
            int childMeasuredHeightSpec = MeasureSpec.makeMeasureSpec(measuredHeight, MeasureSpec.EXACTLY);
            int childMeasuredWidthSpec = MeasureSpec.makeMeasureSpec(w - 100, MeasureSpec.EXACTLY);
            childView.measure(childMeasuredWidthSpec, childMeasuredHeightSpec);
        }
        setMeasureAllChildren(true);
        setMeasuredDimension(w, h);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        int childCount = getChildCount();

        for (int i = childCount - 1; i >= 0; i--) {
            View child = getChildAt(i);
            child.setTranslationX((childCount - i) * 6);
            child.setTranslationY((childCount - i) * 6);
            child.setTranslationZ((childCount - i) * 10);
            if (i % 2 == 0) {
                getChildAt(i).setRotation(-(float) (i * 1.2));
            } else {
                getChildAt(i).setRotation((float) (i * 1.2));
            }

        }


    }


    /**
     * 设置 列表适配器
     *
     * @param adapter 适配器
     */
    public void setAdapter(RecyclerView.Adapter adapter) {
        mAdapter = adapter;
        for (int i = 0; i < adapter.getItemCount(); i++) {
            int viewType = adapter.getItemViewType(i);
            RecyclerView.ViewHolder holder = adapter.createViewHolder(this, viewType);

            adapter.bindViewHolder(holder, i);
            addView(holder.itemView);
        }
        postInvalidate();
        requestLayout();
    }


    private void clearShadow(View v) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            v.setOutlineAmbientShadowColor(Color.TRANSPARENT);
            v.setOutlineSpotShadowColor(Color.TRANSPARENT);
        }
    }


    /**
     * 记录 手指开始滑动的位置
     */
    private float startX = 0;


    /**
     * 标记是否是重新一次的按下
     */
    private boolean pointerIsDown = false;


    @Override
    public boolean onTouchEvent(MotionEvent event) {

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                pointerIsDown = true;
                startX = event.getX();
                break;
            case MotionEvent.ACTION_MOVE:
                Log.e(TAG, "mActionCardNo " + mActionCardNo);
                if (!pointerIsDown) {
                    return true;
                }
                if (mActionCardNo >= getChildCount()) {
                    return true;
                }
                View translateView = getChildAt(mActionCardNo);
                float moveX = event.getX();
                float moveY = event.getY();
                mMoveDistance = moveX - startX;
                float rotation = translateView.getRotation();
                if (startX < moveX) {
                    Log.d(TAG, "右滑====");
                    rotation = rotation + 1;
                    if (rotation < 10) {
                        translateView.setRotation(rotation);
                    }
                } else {
                    Log.d(TAG, "左滑====");
                    rotation -= 1;
                    if (rotation > -10) {
                        translateView.setRotation(rotation);
                    }
                }
                if (translateView.getLayoutParams().width == -1) {
                    translateView.getLayoutParams().width = translateView.getMeasuredWidth();
                }
                // 右滑动
                if (mMoveDistance >= translateView.getLayoutParams().width / 4f) {
                    Log.e(TAG, "mMoveDistance : " + mMoveDistance);
                    postDelayed(() -> {
                        removeView(translateView);
                    }, 100);
                    if (this.listener != null) {
                        listener.onChange(true, false, getChildCount() == 0, getChildCount() - 1);
                    }
                    // 回溯状态
                    pointerIsDown = false;
                    return true;
                }

                // 左边滑动
                if (mMoveDistance < (float) -translateView.getLayoutParams().width / 4f) {
                    Log.e(TAG, "mMoveDistance : " + mMoveDistance);
                    postDelayed(() -> {

                        removeView(translateView);
                    }, 100);

                    if (this.listener != null) {
                        Log.e(TAG, "getChildCount() " + getChildCount());
                        listener.onChange(false, true, getChildCount() == 0, getChildCount() - 1);
                    }

                    // 回溯状态
                    pointerIsDown = false;
                }
                translateView.setTranslationX(mMoveDistance);
                break;
            case MotionEvent.ACTION_UP:
                pointerIsDown = false;
                break;
        }
        return true;
    }


    public void setScrollerListener(IScrollListener scrollerListener) {
        this.listener = scrollerListener;
    }

}
